package com.k8.common.aop.internal.interceptor;

import com.k8.common.aop.internal.advice.AdviceOrderEnum;
import com.k8.common.aop.internal.advice.AfterAdvice;
import com.k8.common.aop.internal.invocation.MethodInvocation;
import com.k8.common.util.AopUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/*
* 参数需要创建的时候就保存好
* invocation.proceed 调用到最后可能会调别的动态代理的类的方法，会修改localInvocation的值
* 参数获取要在proceed之前
* */

public class AfterMethodInterceptor extends ProxyMethodExecutor implements  AfterAdvice {

    @Override
    boolean judgeArgument(Parameter parameter,Method targetMethod) {
        return AopUtil.judgeJoinAdviceArgs(parameter, AdviceOrderEnum.After,targetMethod);
    }

    @Override
    public int getAdviceOrder() {
        return AfterAdvice.super.getAdviceOrder();
    }

    public AfterMethodInterceptor(Object target, Method targetMethod) {
        super(target, targetMethod);
    }

/*    @Override
    public void preInvokeProceed() {
        Object[] arguments=new Object[super.getAdviceMethodParas().length];
        int joinPointIndex1 = super.getJoinPointIndex();
        if (joinPointIndex1>=0){
            MethodInvocation methodInvocation = ExposeInvocationInterceptor.currentMethodInvocation();
            if (methodInvocation instanceof ReflectiveMethodInvocation pmi){
                arguments[joinPointIndex1]=pmi.getJoinPoint();
            }
        }
        super.setCacheParas(arguments);
    }*/

    @Override
    public Object invoke0(MethodInvocation invocation) throws InvocationTargetException, IllegalAccessException {
        Throwable throwable = null;
        Object result = null;
        try {
            result = invocation.proceed();
            return result;
        } catch (Throwable e) {
            throwable = e;
            throw new RuntimeException(e);
        } finally {
            super.invokeAdvice(result);
        }
    }
}
